<template>
  <!-- 用户注册 -->
  <el-form :model="formQuery" :rules="rules" ref="formRef">
    <h1>欢迎登录到ButVan's 博客</h1>
    <!-- 登录 -->
    <div class="login" v-if="loginOrSignHide">
      <p class="tip">请登录您的账号</p>
      <el-form-item label="昵称" prop="username">
        <el-input
          placeholder="请输入您的昵称"
          v-model="formQuery.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input
          placeholder="请输入您的邮箱"
          v-model="formQuery.userEmail"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="emailCode">
        <el-input placeholder="输入邮箱验证码" v-model="formQuery.emailCode">
          <template #append>
            <el-button @click="getEmailCode">{{
              codeInputValue === 0 ? "获取邮箱验证码" : codeInputValue
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
    </div>
    <!-- 注册 -->
    <div class="sign" v-else>
      <div class="tip">请注册您的账号</div>
      <el-form-item label="昵称" prop="username">
        <el-input
          placeholder="输入您的昵称"
          v-model="formQuery.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input
          placeholder="输入您的邮箱"
          v-model="formQuery.userEmail"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="emailCode">
        <el-input placeholder="输入邮箱验证码" v-model="formQuery.emailCode">
          <template #append>
            <el-button @click="getEmailCode">{{
              codeInputValue === 0 ? "获取邮箱验证码" : codeInputValue
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :action="serverUploadImg"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </div>
    <el-form-item>
      <el-button
        @click="loginOrSign"
        style="
          width: 100%;
          background-color: #97cadb;
          border: none;
          color: #fff;
          font-size: 14px;
        "
        >{{ initButValue }}</el-button
      >
    </el-form-item>
    <el-form-item>
      <el-button
        @click="goSign"
        style="width: 100%; font-size: 14px; font-weight: 400; color: black"
      >
        {{ initButValue2 }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, useTemplateRef, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { serverStore } from "@/stores/server";
import { ElMessage } from "element-plus";
import { getEmailCodeService, userLoginOrSignService } from "@/api/Login";
import {
  setUserInfoLocalStorage,
  setUserNameWithUserEmail,
} from "@/utils/UserInfoStore";

const { serverUploadImg } = serverStore();

const codeInputValue = ref(0);
const loginOrSignHide = ref(true);
const initButValue = ref("登录");
const initButValue2 = ref("还没有账号去注册");

/**
 * 获取邮箱验证码
 */
const codeController = ref(1);
const getEmailCode = () => {
  if (formQuery.value.userEmail === "") {
    // 未输入邮箱
    ElMessage.error("请输入邮箱");
    return false;
  }
  getEmailCodeService(formQuery.value.userEmail).then(() => {
    let timer;
    if (codeController.value === 1) {
      codeInputValue.value = 60;
      codeController.value = 0;
      timer = setInterval(() => {
        codeInputValue.value--;
        if (codeInputValue.value === 0) {
          clearInterval(timer);
          codeController.value = 1;
        }
        console.log(codeController.value);
      }, 1000);
    }
  });
};
watch(codeInputValue, (newValue) => {
  codeInputValue.value = newValue;
});

/**
 * 表单数据
 */
const form = useTemplateRef("formRef");
const formQuery = ref({
  username: "",
  userEmail: "",
  emailCode: "",
  headerUrl: "",
});
// 表单校验
const rules = {
  username: [
    {
      required: true,
      message: "昵称不能为空",
      trigger: "blur",
    },
  ],
  userEmail: [
    {
      required: true,
      message: "邮箱不能为空",
      trigger: "blur",
    },
  ],
  emailCode: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
  ],
};

// 登录或者是注册
const loginOrSignController = ref(1);
const loginOrSign = () => {
  if (loginOrSignController.value === 1) {
    // 说明是登录账号
    form.value.validate(async (valid) => {
      if (valid) {
        console.log("登录", formQuery.value);
        const res = await userLoginOrSignService(formQuery.value);
        setUserInfoLocalStorage(res.data);
        const nameWithEmail = {
          username: formQuery.value.username,
          userEmail: formQuery.value.userEmail,
        };
        setUserNameWithUserEmail(nameWithEmail);
      }
    });
  } else {
    // 注册账号
    form.value.validate((valid) => {
      if (valid) {
        console.log("注册", formQuery.value);
        formQuery.value.headerUrl = imageUrl.value;
        userLoginOrSignService(formQuery.value).then(() => {
          imageUrl.value = "";
          initButValue.value = "注册";
          initButValue2.value = "去登陆";
          loginOrSignHide.value = false;
          signBtnController.value = 1;
          loginOrSignController.value = 0;
          formQuery.value = {
            username: "",
            userEmail: "",
            emailCode: "",
            headerUrl: "",
          };
        });
      }
    });
  }
};
// 去注册
const signBtnController = ref(0);
const goSign = () => {
  if (signBtnController.value === 0) {
    // 前往注册页面
    initButValue.value = "注册";
    initButValue2.value = "去登陆";
    loginOrSignHide.value = false;
    signBtnController.value = 1;
    loginOrSignController.value = 0;
    formQuery.value = {
      username: "",
      userEmail: "",
      emailCode: "",
      headerUrl: "",
    };
  } else {
    // 返回登录页面
    initButValue.value = "登录";
    initButValue2.value = "还没有账号去注册";
    loginOrSignHide.value = true;
    signBtnController.value = 0;
    loginOrSignController.value = 1;
    formQuery.value = {
      username: "",
      userEmail: "",
      emailCode: "",
      headerUrl: "",
    };
  }
};

/**
 * 头像上传
 */
const imageUrl = ref("");
// 上传成功调用的方法
const handleAvatarSuccess = (res) => {
  console.log("响应数据", res);
  imageUrl.value = res.msg;
};
</script>

<style lang="scss" scoped>
h1 {
  text-align: center;
  color: black;
}
.tip {
  text-align: center;
  margin-bottom: 10px;
  font-size: 14px;
}
.avatar-uploader .avatar {
  width: 52px;
  height: 52px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 22px;
  color: #8c939d;
  width: 36px;
  height: 36px;
  text-align: center;
}
</style>